﻿using RabbitMQ.Client;

namespace Leo.Common.RabbitMQ
{
    /// <summary>
    /// 消息拒绝策略
    /// </summary>
    public class MessageRejectStrategy
    {
        private string Destination { get; set; }
        internal RabbitQueueInfo RelatedQueue { get; }
        public bool Temporary { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="destination">目的地</param>
        /// <param name="queue">队列信息</param>
        /// <param name="temporary">临时状态</param>
        public MessageRejectStrategy(string destination, RabbitQueueInfo queue, bool temporary)
        {
            this.Destination = destination;
            this.RelatedQueue = queue;
            this.Temporary = temporary;
        }


        /// <summary>
        /// 获取死信交换机
        /// </summary>
        /// <returns></returns>
        internal RabbitExchangeInfo GetDeadExchange()
        {
            RabbitExchangeInfo rabbitExchangeInfo;

            if (!string.IsNullOrEmpty(this.Destination))
            {
                PublicationAddress publicationAddress = PublicationAddress.Parse(this.Destination);

                ExchangeWorkMode exchangeType = Enum.Parse<ExchangeWorkMode>(publicationAddress.ExchangeType, true);

                rabbitExchangeInfo = new RabbitExchangeInfo(publicationAddress.ExchangeName, exchangeType);
            }
            else
            {
                RabbitQueueBinder rabbitQueueBinder = this.RelatedQueue.Binders.FirstOrDefault<RabbitQueueBinder>();
                rabbitExchangeInfo = ((rabbitQueueBinder != null) ? rabbitQueueBinder.GenDeadExchange() : null);
            }


            if (rabbitExchangeInfo != null)
            {
                rabbitExchangeInfo.redeclared = this.RelatedQueue.redeclared;
                if (this.Temporary)
                {
                    rabbitExchangeInfo.AutoDelete = true;
                    rabbitExchangeInfo.Durable = false;
                }
            }
            return rabbitExchangeInfo;
        }
    }
}
